package com.hailiao.hailiaolibrary.Util;

import android.os.AsyncTask;
import android.util.Log;

import com.hailiao.hailiaolibrary.hailiaoInterface.HlMessageReceiveInterface;
import com.hailiao.hailiaolibrary.hailiaoInterface.HlSendMessageInterface;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by BYH on 2016/4/22.
 */
public class HailiaoMessageUtil {
    private static HailiaoMessageUtil ourInstance = new HailiaoMessageUtil();

    //发送短报文要调用的地址
    private static String sendBdMessageUrl = "http://api.hellobeidou.com/api/msg/send";
    //查询最新接收消息要调用的地址
    private static String checkBdMessageUrl = "http://api.hellobeidou.com/api/msg/list/receive";
    //注册地址
    private static String hailiaoSDKUrl = "http://114.215.239.119:8989/bdmob/";
    final private String SOURCE = "hwzs";

    private String sendSubmit(String userName, String IDCard, String phone) {
        try {
            sign = MD5.parseStrToMd5L32("IDCard=" + IDCard + "&key=6a518c6be8e0dddc" + "&phone=" + phone + "&source=" + SOURCE
            + "&username=" + userName);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("IDCard", IDCard));
            nvps.add(new BasicNameValuePair("phone", phone));
            nvps.add(new BasicNameValuePair("username", userName));
            nvps.add(new BasicNameValuePair("source", SOURCE));
            nvps.add(new BasicNameValuePair("sign", sign));
            String result = doPost(nvps, hailiaoSDKUrl + "submitInfo");
            return result;
        } catch (Exception e) {
            Log.e("HailiaoMessageUtil", e.getMessage());
            return null;
        }
    }

    public String changeSos(String userName, String sosName, String sosName2, String sosName3,  String sosMob, String sosMob2, String sosMob3) {
        try {
            sign = MD5.parseStrToMd5L32("key=6a518c6be8e0dddc" + "&username=" + userName);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("sosName1", sosName));
            nvps.add(new BasicNameValuePair("sosName2", sosName2));
            nvps.add(new BasicNameValuePair("sosName3", sosName3));
            nvps.add(new BasicNameValuePair("sosMob1", sosMob));
            nvps.add(new BasicNameValuePair("sosMob2", sosMob2));
            nvps.add(new BasicNameValuePair("sosMob3", sosMob3));
            nvps.add(new BasicNameValuePair("username", userName));
            nvps.add(new BasicNameValuePair("sign", sign));
            String result = doPost(nvps, hailiaoSDKUrl + "changeSosForSdk");
            return result;
        } catch (Exception e) {
            return null;
        }
    }

    public void sendSubmitRequest(String userName, String IDCard, String phone,final HlSendMessageInterface hlSendMessageInterface){
        final String muserName = userName;
        final String mIDCard = IDCard;
        final String mphone = phone;
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                return HailiaoMessageUtil.getInstance().sendSubmit(muserName, mIDCard, mphone);
            }

            @Override
            protected void onPostExecute(String s) {
                if (s == null){
                    hlSendMessageInterface.onMessageSendFailed(s);
                }else {
                    JSONObject resultJson = null;
                    try {
                        resultJson = new JSONObject(s);
                        String status = resultJson.getString("status");
                        if (status.equals("OK")) {
                            hlSendMessageInterface.onMessageSendSuccess(s);
                        }else {
                            hlSendMessageInterface.onMessageSendFailed(s);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.execute((Void) null);
    }

    public void sendChangeSOSRequest(String userName, String sosName, String sosName2, String sosName3,  String sosMob, String sosMob2, String sosMob3,final HlSendMessageInterface hlSendMessageInterface){
        final String muserName = userName;
        final String msosname = sosName;
        final String msosname2 = sosName2;
        final String msosname3 = sosName3;
        final String msosmob = sosMob;
        final String msosmob2 = sosMob2;
        final String msosmob3 = sosMob3;
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                return HailiaoMessageUtil.getInstance().changeSos(muserName, msosname, msosname2, msosname3, msosmob, msosmob2,msosmob3);
            }

            @Override
            protected void onPostExecute(String s) {
                if (s == null){
                    hlSendMessageInterface.onMessageSendFailed(s);
                }else {
                    JSONObject resultJson = null;
                    try {
                        resultJson = new JSONObject(s);
                        String status = resultJson.getString("status");
                        if (status.equals("OK")) {
                            hlSendMessageInterface.onMessageSendSuccess(s);
                        }else {
                            hlSendMessageInterface.onMessageSendFailed(s);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.execute((Void) null);
    }

    //分配的appid
    private static String mAppId;
    //分配的app密钥
    private static String mAppSecret;
    //时间戳
    String timeStamp;
    //sign配合appId+appSecret+timeStamp，MD5生成
    String sign;
    //默认值为零，从最后一条开始查。之后从返回的最新的id去查下一次消息
    String msgId = "0";


    public static HailiaoMessageUtil getInstance() {
        return ourInstance;
    }

    public static void initHailiaoMessageUtil(String appId, String appSecret, String sendUrl, String receiveUrl){
        mAppId = appId;
        mAppSecret = appSecret;
        sendBdMessageUrl = sendUrl;
        checkBdMessageUrl = receiveUrl;
    }

    private HailiaoMessageUtil() {
    }

    /**
     *
     * @param cardNumber  要查询的卡号
     * @param msgId       请输入接收到的最新的消息ID
     * @param intervalTime  循环查询的间隔时间
     * @param hlMessageReceiveInterface  回调接口
     */
    public void roundCheckMessage(String cardNumber, String msgId, int intervalTime,
                                  final HlMessageReceiveInterface hlMessageReceiveInterface){
        final String mCardNumber = cardNumber;
        final String[] mMsgId = {msgId};
        final int mIntervalTime = intervalTime;
        new Thread(){
            @Override
            public void run() {
                while (true){
                    new AsyncTask<Void, Void, String>() {
                        @Override
                        protected String doInBackground(Void... params) {
                            return HailiaoMessageUtil.getInstance().mCheckBdMessage(mCardNumber, mMsgId[0]);
                        }

                        @Override
                        protected void onPostExecute(String s) {
                            if (s == null) {
                                hlMessageReceiveInterface.onReceiveMessageFailed(s);
                            } else {
                                JSONObject resultJson = null;
                                try {
                                    resultJson = new JSONObject(s);

                                    String status = resultJson.getString("status");
                                    if (status.equals("OK")) {
                                        JSONObject object = resultJson.getJSONObject("result");
                                        //每次用上请求的id改为最新的MsgId来请求.
                                        mMsgId[0] = object.getString("lastMsgId");
                                        hlMessageReceiveInterface.onReceiveMessageSuccess(s);
                                    }else {
                                        hlMessageReceiveInterface.onReceiveMessageFailed(s);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }.execute((Void) null);
                    try{
                        sleep(mIntervalTime);
                    }catch (Exception e){
                        Log.e("HailiaoMessageUtil", e.getMessage());
                    }
                }
            }
        }.start();

    }

    /**
     *
     * @param channelId    租用通道ID标识
     * @param toCardNumber 发送至目标的卡号
     * @param dataType     选择发送的类型：混编 ：1 汉字：2  代码：3
     * @param content      内容：可输入76个字节(字母，标点符号均算一个字节，汉字算2个字节)
     * @param hlSendMessageInterface  回调接口
     */
    public void sendBdMessage( String channelId, String toCardNumber, String dataType, String content,
                               final HlSendMessageInterface hlSendMessageInterface){
        final String mChannelId = channelId;
        final String mToCardNumber = toCardNumber;
        final String mContent = content;
        final String mDataType = dataType;
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                return HailiaoMessageUtil.getInstance().mSendBdMessage(mChannelId, mToCardNumber, mDataType, mContent);
            }

            @Override
            protected void onPostExecute(String s) {
                if (s == null){
                    hlSendMessageInterface.onMessageSendFailed(s);
                }else {
                    JSONObject resultJson = null;
                    try {
                        resultJson = new JSONObject(s);
                        String status = resultJson.getString("status");
                        if (status.equals("OK")) {
                            hlSendMessageInterface.onMessageSendSuccess(s);
                        }else {
                            hlSendMessageInterface.onMessageSendFailed(s);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.execute((Void) null);

    }

    /**
     * 查询此卡号最新接收消息
     * @param cardNumber  要查询的卡号
     * @param msgId       请输入接收到的最新的ID
     * @param hlMessageReceiveInterface
     */
    public void checkBdMessage(String cardNumber, String msgId,
                               final HlMessageReceiveInterface hlMessageReceiveInterface){
        final String mCardNumber = cardNumber;
        final String mMsgId = msgId;
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                return HailiaoMessageUtil.getInstance().mCheckBdMessage(mCardNumber, mMsgId);
            }

            @Override
            protected void onPostExecute(String s) {
                if (s == null){
                    hlMessageReceiveInterface.onReceiveMessageFailed(s);
                }else {
                    hlMessageReceiveInterface.onReceiveMessageSuccess(s);
                }
            }
        }.execute((Void) null);

    }
    /**
     *使用通道来发送短报文
     * @param channelId    租用通道ID标识
     * @param toCardNumber 发送至目标的卡号
     * @param content      内容：可输入76个字节(字母，标点符号均算一个字节，汉字算2个字节)
     * @return
     */
    private String mSendBdMessage(String channelId, String toCardNumber, String dataType, String content) {
        try {
            timeStamp = String.valueOf(System.currentTimeMillis());
            sign = MD5.parseStrToMd5L16(mAppId + mAppSecret + timeStamp);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("identifier", channelId));
            nvps.add(new BasicNameValuePair("toCard", toCardNumber));
            nvps.add(new BasicNameValuePair("content", content));
            nvps.add(new BasicNameValuePair("appId", mAppId));
            nvps.add(new BasicNameValuePair("sign", sign));
            nvps.add(new BasicNameValuePair("appSecret", mAppSecret));
            nvps.add(new BasicNameValuePair("timeStamp", timeStamp));
            nvps.add(new BasicNameValuePair("dataType", dataType));
            String result = doPost(nvps, sendBdMessageUrl);
            return result;
        } catch (Exception e) {
            Log.e("HailiaoMessageUtil", e.getMessage());
            return null;
        }
    }

    /**
     * 查询此卡号最新接收消息
     * @param cardNumber
     * @return
     */
    private String mCheckBdMessage(String cardNumber, String msgId) {
        try {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("toCard", cardNumber));
            nvps.add(new BasicNameValuePair("appId", mAppId));
            nvps.add(new BasicNameValuePair("sign", sign));
            nvps.add(new BasicNameValuePair("appSecret", mAppSecret));
            nvps.add(new BasicNameValuePair("timeStamp", timeStamp));
            nvps.add(new BasicNameValuePair("msgId", msgId));
            String result = doPost(nvps, checkBdMessageUrl);
            return result;
        } catch (Exception e) {
            Log.e("HailiaoMessageUtil", e.getMessage());
            return null;
        }
    }




    private String doPost(List<NameValuePair> nvps, String url) throws Exception {
        try {
            HttpClient httpClient = new DefaultHttpClient();
            // HttpPost 实现 HttpUriRequest 接口,HttpUriRequest接口 继承 HttpRequest
            HttpPost httpPostReq = new HttpPost(url);

            httpPostReq.setEntity(new UrlEncodedFormEntity(nvps, "utf8"));
            HttpResponse resp = httpClient.execute(httpPostReq);

            if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
                StringBuffer result = new StringBuffer();
                String inputLine = null;
                while ((inputLine = reader.readLine()) != null) {
                    result.append(inputLine);
                }
                System.out.println(result.toString());//示例：{"status":"OK","message":"提交建议成功","result":true}
                return result.toString();
            } else {
                System.out.println(resp.getStatusLine().getStatusCode());
                return null;
            }
        } catch (Exception e) {
            Log.e("HailiaoMessageUtil", e.getMessage());
            return null;
        }
    }
}
